/**
 * 评论media框,在面板使用
 */

import React from 'react';
import MarkdownIt from 'markdown-it';
import utils from 'utils';
import hljs from 'utils/hl.js';
import './inlineComment.scss';
import TextAvatar from '@txdfe/at-text-avatar';
import { Title } from '@alife/devops-ui';
import milt from 'markdown-it-link-target';
import { filterXSS } from 'xss';
import { Tag } from '@teamix/ui';
import intl from '../../../../../../../../../../../locale';

const md = new MarkdownIt({
  html: true,
  highlight(str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(lang, str).value;
      } catch (__) {
        return '';
      }
    }

    return ''; // 使用额外的默认转义
  },
}).use(milt, {
  target: '_blank',
});

const { pathResource } = window.FORCE;

const colors = { Major: 'blue', Critical: 'orange', Blocker: 'red' };
export default class CommentMedia extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isHover: false, // 是否悬浮
    };
  }

  renderApply = () => {
    const { comment } = this.props;
    const hasPermission = pathResource.isArchive === 'false';
    const isYundou = comment._comment_type === 'issue';
    // TODO 自己的评论可以编辑和删除(接口暂时不支持)
    // 有草稿也能回复,hover显示回复，否则显示时间,过期不能回复
    // 云豆信息不显示回复，整体评论和云豆回复默认outdated为true,但是没有行号
    if (!hasPermission || !this.state.isHover || (comment.outdated && comment.line) || isYundou) {
      return <span>{utils.getBeautyTime(comment.created_at)}</span>;
    } else {
      return (
        <a
          onClick={(e) => {
            e.stopPropagation();
            this.props.replyFn && this.props.replyFn(comment);
          }}
          className="reply-btn"
        >
          {intl.get({
            id: 'code-assets.components.commentMedia.panelComment.Response',
            defaultMessage: '回复',
          })}
        </a>
      );
    }
  };

  // 整体评论，没有行信息，行内有
  renderMain = () => {
    const { comment } = this.props;
    const isYundou = comment._comment_type === 'issue';
    const { issue } = comment;
    const body = (
      <div className="comment-new-media-whole-comment">
        <div className="comment-new-media-whole-comment-left comment-content">
          {isYundou ? (
            <div className="issue-detail">
              <span className="issue-detail-tag">
                <Tag color={colors[issue.level]}>{issue.level}</Tag>
              </span>
              <span className="issue-detail-title" title={issue.title}>
                {issue.title}
              </span>
            </div>
          ) : (
            <div
              className="comment-content markdown-body"
              dangerouslySetInnerHTML={{
                __html: filterXSS(md.render(comment.note || ''), {
                  onIgnoreTagAttr: (_, name, value) => {
                    return `${name}=${value}`;
                  },
                }),
              }}
            />
          )}
        </div>
      </div>
    );

    return (
      <div className="panel-comment-item">
        <div className="panel-comment-item-left">
          <div className="author-avatar">
            <TextAvatar
              text={(comment.author && comment.author.name) || ''}
              image={(comment.author && comment.author.avatar_url) || ''}
              radius="50%"
              size="xs"
            />
          </div>
          <div className="panel-line" />
        </div>
        <div className="panel-comment-item-right">
          <div className="user-info">
            <div className="user-info-left">
              <div className="name" style={{ maxWidth: 50 }}>
                <Title
                  trigger={<span>{(comment.author && comment.author.name) || ''}</span>}
                  align="t"
                >
                  {(comment.author && comment.author.name) || ''}
                </Title>
              </div>
              {isYundou ? (
                <div className="bot-tag">
                  <Tag style={{ margin: '0 4px' }}>bot</Tag>
                </div>
              ) : null}
              <div className="time">{this.renderApply()}</div>
            </div>
          </div>
          {body}
        </div>
      </div>
    );
  };

  render() {
    const { comment } = this.props;

    if (!comment) {
      return null;
    }
    return (
      <div
        className="comment-new-media"
        onMouseEnter={() => {
          this.setState({
            isHover: true,
          });
        }}
        onMouseLeave={() => {
          this.setState({
            isHover: false,
          });
        }}
      >
        {this.renderMain()}
      </div>
    );
  }
}
